package com.diaohw.module.system.service.impl;

import com.diaohw.module.system.mapper.RoleMapper;
import com.diaohw.module.system.obj.dto.RoleDto;
import com.diaohw.module.system.obj.entity.Role;
import com.diaohw.module.system.obj.mapstruct.RoleMapstruct;
import com.diaohw.module.system.obj.query.RoleQuery;
import com.diaohw.module.system.obj.vo.RoleVo;
import com.diaohw.module.system.service.RoleService;
import com.diaohw.platform.common.exception.GlobalException;
import com.diaohw.platform.common.obj.page.PageResultVo;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.diaohw.platform.framework.authorization.AuthorizationHeaderConst.SUPER_ADMIN;

/**
 * <p>
 * 角色 服务实现类
 * </p>
 *
 * @author D-Hw
 * @since 2024-07-05
 */
@Service
public class RoleImpl implements RoleService {

    @Resource
    private RoleMapper roleMapper;

    @Override
    public RoleVo create(RoleDto data) {
        Role model = RoleMapstruct.INSTANCE.dtoToEntity(data);
        roleMapper.insert(model);
        return RoleMapstruct.INSTANCE.entityToVo(model);
    }

    @Override
    public RoleVo update(String id, RoleDto data) {
        Role model = RoleMapstruct.INSTANCE.dtoToEntity(data);
        model.setId(id);
        roleMapper.update(model);
        return RoleMapstruct.INSTANCE.entityToVo(model);
    }

    @Override
    public Boolean menu(String roleId, List<String> menuIds) {
        Role role = new Role();
        role.setId(roleId);
        role.setMenuId(menuIds);
        return roleMapper.update(role) > 0;
    }

    @Override
    public Boolean delete(String id) {
        Role role = roleMapper.selectOneById(id);
        if (SUPER_ADMIN.equals(role.getRoleCode())) {
            throw new GlobalException("不能删除超级管理员");
        }

        return roleMapper.deleteById(id) > 0;
    }

    @Override
    public RoleVo detail(String id) {
        return RoleMapstruct.INSTANCE.entityToVo(roleMapper.selectOneById(id));
    }

    @Override
    public List<RoleVo> findByList(RoleQuery query) {
        QueryWrapper wrapper = RoleMapper.createWrapper(query);
        return RoleMapstruct.INSTANCE.entityToVo(roleMapper.selectListByQuery(wrapper));
    }

    @Override
    public PageResultVo<RoleVo> findByPage(RoleQuery query) {
        QueryWrapper wrapper = RoleMapper.createWrapper(query);
        Page<Role> page = roleMapper.paginate(query.getPageIndex(), query.getPageSize(), wrapper);
        return PageResultVo.create(page.getTotalRow(), RoleMapstruct.INSTANCE.entityToVo(page.getRecords()));
    }

}
